library(ggplot2)
library(dplyr)
library(modelsummary)
library(kableExtra)
library(stringr)
library(fixest)
library(stargazer)
library(gridExtra)
library(flextable)


survey_long <- readRDS("data/df_long.rds")

survey_long <- survey_long %>% filter(d_affiliated == 1 & d_ownparty == 0)
survey_long <- survey_long %>% 
  group_by(meta_UUID) %>%
  mutate(N_ind = n(), 
         weights = meta_Weight / N_ind,
         weights_manual = manual_weights2 / N_ind) 


########### Regression analyses

country_df <- data.frame(parties = unique(survey_long$evaluated_party),
                         coef = NA, 
                         se = NA, 
                         pvalue = NA)


models <- list()

for(i in 1:nrow(country_df)){
  party <- country_df$parties[i]
  
  mod <- feols(close_num ~ feeling_toward | meta_UUID, survey_long %>% filter(party_affil != party), 
               weights = survey_long$weights[survey_long$party_affil != party])
  country_df$coef[i] <- mod$coefficients
  country_df$se[i] <- mod$se[1]
  country_df$pvalue[i] <- as.character(mod$coeftable$`Pr(>|t|)`)
  
  models[[i]] <- mod
  
  print(i)
}

country_df$pvalue <- ifelse(country_df$pvalue == "0", "0.000", country_df$pvalue)
country_df$pvalue <- paste0("(", country_df$pvalue, ")")
country_df$parties <- factor(country_df$parties, 
                                     levels = country_df$parties[with(country_df, 
                                                                      order(coef))])



pd <- position_dodge(0.5)

regs <- ggplot(country_df, aes(x = parties, ymin = coef - se*1.96, y = coef, ymax = coef + se*1.96)) + 
  geom_point(position = pd, shape = 21, fill = 'white') + 
  geom_errorbar(width = 0, position = pd) + 
  xlab("") + 
  ylab("Feeling coefficient") +
  geom_text(aes(label = pvalue), nudge_y = 0.01, inherit.aes = T, size = 3.5) +
  coord_flip() +
  theme_bw() +
  theme(text = element_text(size = 14)) 

regs

ggsave("figures/FigureA2.jpeg", plot = regs,
       height = 12, width = 8, dpi = 600)
